<?php
declare(strict_types=1);

namespace Service\GoodsClassService;

use Service\BaseService;
use Service\CountryService\CountryService;
use Service\Code\Normal;
use Service\HelperService\Common;
use App\Model\BbcModel\GoodsClass;
use Service\CacheService\CacheProviderService as Cache;
use Hyperf\HttpServer\Contract\RequestInterface;

/**
 * 分类
 * @author hj
 */
class ClassService extends BaseService {

    /**
     * 获取某个分类的子级
     */
    public static function getClassChildren($pid = 0, $cid = 0): array {
        return self::getClass($pid, $cid, false);
    }

    /**
     * 获取树形分类
     */
    public static function getClassTree($pid = 0, $cid = 0): array {
        return self::getClass($pid, $cid);
    }

    /**
     * 获取分类
     * @param int $pid
     * @param int $cid
     * @param bool $is_tree true返回树形  fasle返回子级
     * @author: hj
     */
    protected static function getClass($pid = 0, $cid = 0, $is_tree = true){
        $fields = ['id', 'name', 'icon', 'pid','description'];
        $allClass = GoodsClass::where('df', 0)->where('show', 1)->where('cid', $cid)->select($fields)->orderBy('sort', 'desc')->get()->toArray();
        if(!$allClass){
            return Normal::returnCode(Normal::FAIL, '分类不存在');
        }

        foreach ($allClass as &$item) {
            if( !empty($item['icon']) && strpos($item['icon'],'http') === false ) {
                $item['icon'] = Common::$pre_image_url. $item['icon'];
            }
        }
        unset($item);
        if($is_tree === true){
            $allClass = self::tree($allClass, $pid, 'id', 'pid');
        }else{
            $allClass = all_sub($allClass, $pid, 'id', 'pid');
        }
        $allClass = array_map(function($item){
            return [
                'id'    => $item['id'],
                'name'  => $item['name'],
                'icon'  => $item['icon'],
                'description' => $item['description'] ?? '',
                'son'  => empty($item['son'])?[]:$item['son'],
            ];
        }, $allClass);
        return Normal::returnCode(Normal::SUC, '获取成功', $allClass);
    }

    /**
     * 专属树形处理
     */
    public static function tree($arr, $pid, $id_k, $pid_k){
        $tree  =   [];
        foreach ($arr as $k => $v) {
            if ($v[$pid_k] == $pid) {
                unset($arr[$k]);
                $temp         =   $v;
                $temp['son']  =   self::tree($arr, $v[$id_k], $id_k, $pid_k);
                $tree[]       =   $temp;
            }
        }
        return $tree;
    }
    
}